<?php

namespace App\Service;

use App\Jobs\Notification;
use App\Library\ChargeCache;

class ChargeService
{
    use ChargeCache;

    /**
     * token认证
     * @param $params
     * @param $privData
     * @return array
     */
    public function token($params, $privData)
    {
        if (empty($privData)) {
            $returnData['FailReason'] = 1;
            $returnData['SuccStat'] = 1;
        } else {
            $currentTime = time();
            $token = strtoupper(md5($currentTime));
            $returnData['AccessToken'] = md5($token);
            $returnData['TokenAvailableTime'] = 7200;
            $returnData['SuccStat'] = 0;
            $returnData['FailReason'] = 0;
        }
        $returnData['OperatorID'] = $params['OperatorID'];
        return $returnData;
    }

    /**
     * 设备认证
     * @param $params
     * @return array
     */
    public function queryEquipAuth($params)
    {
        return [
            'EquipAuthSeq' => $params['EquipAuthSeq'],
            'ConnectorID' => $params['ConnectorID'],
            'FailReason' => 0,
            'SuccStat' => 0,
            'OperatorID' => $params['OperatorID']
        ];
    }

    /**
     * 开始充电
     * @param $params
     * @return mixed
     */
    public function queryStartCharge($params)
    {
        //StartChargeSeqStat 1：启动中2：充电中3：停止中4：已结束5：未知
        //SuccStat 0:成功；1:失败
        //FailReason 失败原因
        //写入充电
        $check = $this->getChargeStatusCache($params['ConnectorID']);
        if ($check) {
            $code = json_decode($check, true);
            $params['StartChargeSeqStat'] = $code['status'];
            $params['SuccStat'] = 0;
            $params['FailReason'] = 0;
        } else {
            $flag = $this->setChargeStatusCache($params['ConnectorID'], 1, $params['StartChargeSeq']);
            if ($flag) {
                $params['StartChargeSeqStat'] = 2;
                $params['SuccStat'] = 0;
                $params['FailReason'] = 0;
            } else {
                $params['SuccStat'] = 1;
                $params['StartChargeSeqStat'] = 2;
                $params['FailReason'] = 0;
                $this->setChargeStatusCache($params['ConnectorID'], 1, $params['StartChargeSeq']);
            }
        }
        return $params;
    }

    /**
     * 结束充电
     * @param $params
     * @return array
     */
    public function queryStopCharge($params)
    {
        $check = $this->getChargeCacle($params['ConnectorID']);
        if (!empty($check)) {
            return [];
        }
        return ['StartChargeSeq' => $params['StartChargeSeq'], 'SuccStat' => 0, 'FailReason' => '','OperatorID'=>$params['OperatorID']];
    }

    /**
     * 查询充电状态
     * @param $params
     * @return array
     */
    public function queryEquipChargeStatus($params)
    {
        return (new NotificationService())->calcChageElc($params['StartChargeSeq']);
    }
}
